#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' main entry '
__author__ = 'pingwu you'

#with 资源语句
#实现上下文管理是通过__enter__和__exit__这两个方法实现的
class Query(object):
    def __init__(self, name):
        self.name = name
    def __enter__(self):
        print('Begin')
        return self    
    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type:
            print('__exit__ Error：'+str(exc_value))
        else:
            print('End')    
    def query(self):
        print('Query info about %s...' % self.name)


from contextlib import contextmanager
class Query22(object):
    def __init__(self, name):
        self.name = name
    def query(self):
        print('Query info about %s...' % self.name)

@contextmanager
def create_query(name):
    print('Begin1111')
    q = Query22(name)
    yield q
    print('End222222')


class Query33(object):
    def __init__(self, name):
        self.name = name
    def query(self):
        print('Query info about %s...' % self.name)
    def close(self):
        print("触发我的close了")

def help_demo():
    print("-----before---------")
    try:
        with Query("我啊") as q:
            print(q)
            raise Exception("异常啊")
    except BaseException as e:
        print("---outer catch----"+str(e))
    print("-----after---------")

    #装饰器装饰后的效果 通过yield分割包装前后 模拟 enter exit
    with create_query('Bob') as q:
        q.query()

    #closing也是一个经过@contextmanager装饰的generator
    #只是对enter / exit 上下文封装，但必须要目标类对象已经实现了close
    from contextlib import closing
    with closing(Query33("开卷考")) as q:
        print("--过程中--")


